<?php

namespace Library\Models;

use \Library\Entities\Inscription;

class InscriptionManager_PDO extends InscriptionManager {

    public function checkMail($user) {
        $sql = 'SELECT email FROM users';

        $requete = $this->dao->query($sql);
        $requete->setFetchMode(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, '\Library\Entities\Inscription');

        foreach ($requete->fetchall() as $row) {
            $mail = $row->email();

            if ($mail === $user) {
                $requete->closeCursor();
                return true;
            } else {
                $requete->closeCursor();
                return false;
            }
        }
    }

    protected function add(Inscription $inscript) {
        $q = $this->dao->prepare('INSERT INTO users 
            SET email = :email, password = :mdp, name = :name, registration_date = NOW(), active_account = 0, activation_key = :activKey');
        $q->bindValue(':email', $inscript->email());
        $q->bindValue(':mdp', $inscript->password());
        $q->bindValue(':name', $inscript->name());
        $q->bindValue(':activKey', $this->createActivationKey());
        $q->execute();
    }

    public function createActivationKey() {
        // Génération de la clef d'activation
        $caracteres = array("a", "b", "c", "d", "e", "f", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
        $caracteres_aleatoires = array_rand($caracteres, 8);
        $activation_key = "";

        foreach ($caracteres_aleatoires as $i) {
            $activation_key .= $caracteres[$i];
        }
        return $activation_key;
    }

}

?>